package com.logicbus.backend.message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;
import com.anysoft.util.compress.Compressor;
import com.anysoft.util.compress.compressor.GZIP;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anysoft.util.IOTools;
import com.logicbus.backend.Context;

import javax.annotation.PostConstruct;

/**
 * 基于Byte消息
 * @author duanyy
 * 
 * @since 1.6.1.1
 * 
 * @version 1.6.1.2 [20141118 duanyy] <br>
 * - 支持MessageDoc的Raw数据功能 <br>
 * @version 1.6.2.1 [20141223 duanyy] <br>
 * - 增加对Comet的支持 <br>
 * 
 * @version 1.6.5.6 [20160523 duanyy] <br>
 * - 淘汰MessageDoc，采用Context替代 <br>
 * - 增加getContentType和getContentLength <br>
 * 
 * @version 1.6.7.9 [20170201 duanyy] <br>
 * - 采用SLF4j日志框架输出日志 <br>
 * 
 * @version 1.6.7.15 [20170221 duanyy] <br>
 * - 输出时设置Content-Length以便支持keepalive <br>
 * 
 * @version 1.6.12.37 [20190626] <br>
 * - 输出内容可以为空 <br>
 *
 * @version 1.6.13.21 [20201021 duanyy] <br>
 * - 支持gzip压缩 <br>
 */
public class ByteMessage implements Message {
	/**
	 * a logger of log4j
	 */
	protected static final Logger logger = LoggerFactory.getLogger(ByteMessage.class);
	/**
	 * 输入的字节流
	 */
	protected byte [] input = null;
	
	/**
	 * 输出的字节流
	 */
	protected byte [] output = null;
	
	/**
	 * content-type
	 */
	protected String contentType = "text/plain";

	private static Compressor gzipCompressor = new GZIP();

	private static boolean gzipSupport = false;

	/**
	 * gzip开启的报文长度
	 */
	private static int gzipEnableLength = 1024;

	static {
		gzipSupport = PropertiesConstants.getBoolean(Settings.get(),"http.byte.gzip",gzipSupport);
		gzipEnableLength = PropertiesConstants.getInt(Settings.get(),"http.gzip.length",gzipEnableLength);
	}

	private boolean isGzipEnable(Context ctx,String header){
		if (!gzipSupport) {
			return false;
		}
		String gzip = ctx.getRequestHeader(header);
		return StringUtils.isNotEmpty(gzip)?gzip.equalsIgnoreCase("gzip"):false;
	}
	
	/**
	 * 获取输入的字节流
	 * @return 输入字节流
	 */
	public byte [] getInput(){return input;}
	
	/**
	 * 设置待输出的字节流数据
	 * @param _output 待输出的数据
	 */
	public void setOutput(byte [] _output){
		output = _output;
	}
	
	public void setContentType(String _contentType){
		contentType = _contentType;
	}
	
	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public long getContentLength() {
		return (input == null ? 0:input.length) + (output == null ? 0:output.length);
	}

	@Override
	public void init(Context ctx) {
		boolean gzipEnable = isGzipEnable(ctx,"Content-Encoding");
		input = ctx.getRequestRaw();
		if (input != null){
			if (input.length > 0 && gzipEnable){
				input = gzipCompressor.decompress(input);
			}
		}else{
			InputStream in = null;
			try {
				in = ctx.getInputStream();
				input = Context.readBytesFromInputStream(in);
				if (input !=null && input.length > 0 && gzipEnable){
					input = gzipCompressor.decompress(input);
				}
			}catch (Exception ex){
				logger.error("Error when reading data from inputstream",ex.getMessage());
			}finally{
				IOTools.close(in);
			}
		}
	}

	@Override
	public void finish(Context ctx,boolean closeStream) {
		boolean gzipEnable = isGzipEnable(ctx,"Accept-Encoding");
		OutputStream out = null;
		try {
			if (output != null) {
				ctx.setResponseContentType(contentType);
				if (gzipEnable && gzipEnableLength < output.length){
					output = gzipCompressor.compress(output);
					ctx.setResponseHeader("Content-Encoding","gzip");
				}
				ctx.setResponseContentLength(output.length);
				out = ctx.getOutputStream();
				if (output != null && out != null) {
					Context.writeToOutpuStream(out, output);
				}
				out.flush();
			}
		}catch (Exception ex){
			logger.error("Error when writing data to output stream",ex.getMessage());
		}finally{
			if (closeStream){
				IOTools.close(out);
			}
		}
	}

}
